/**
 * 
 */
package cn.ad.server.web.spring.service.components.adtraffic;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 流量分发管理
 * @author shinb
 */
@Component
public class AdTrafficDispatcherManager {
	
	/**
	 * 流量分发接口列表，用于保存用于自有流量分发接口实现
	 */
	private Set<ITrafficDispatcher> trafficDispatchers;
	
	
	/**
	 * 默认的流量分发器
	 */
	private ITrafficDispatcher defaultDispatcher;
	
	
//	@Autowired
//	GDTTrafficDispatcher gdtTrafficDispatcher;
	
	@Resource(name="trafficDispatcher")
	ITrafficDispatcher trafficDispatcher;
	
	public AdTrafficDispatcherManager() {
		super();
		defaultDispatcher = trafficDispatcher;
	}

	/**
	 * 分发流量请求
	 * @param request 流量请求，代表一个需要分发的广告请求
	 * @return 分发请求响应结果
	 * @throws TrafficDispatchException 
	 */
	public TrafficResponse dispatchTraffic(TrafficRequest request) throws TrafficDispatchException{
		ITrafficDispatcher dispatcher = matchDispatcher(request);
		if(dispatcher != null){
			return dispatcher.dispatch(request);
		}else{
			throw new TrafficDispatchException("没有找到匹配的流量分发接口.");
		}
	}

	/**
	 * 获取一个流量分发接口
	 * 流量分发接口将根据具体选择策略来决定
	 * @param request
	 * @return
	 */
	private ITrafficDispatcher matchDispatcher(final TrafficRequest request){
		if(getTrafficDispatchers() == null || getTrafficDispatchers().size() == 0){
			//返回默认流量分发接口
			return getDefaultDispatcher();
		}else{
			// TODO 增加从流量分发接口列表中匹配分发接口代码
			return null;
		}
	}

	public Set<ITrafficDispatcher> getTrafficDispatchers() {
		return trafficDispatchers;
	}

	public void setTrafficDispatchers(Set<ITrafficDispatcher> trafficDispatchers) {
		this.trafficDispatchers = trafficDispatchers;
	}

	public ITrafficDispatcher getDefaultDispatcher() {
		if(defaultDispatcher == null){
			defaultDispatcher = trafficDispatcher;
		}
		return defaultDispatcher;
	}

	public void setDefaultDispatcher(ITrafficDispatcher defaultDispatcher) {
		this.defaultDispatcher = defaultDispatcher;
	}
}
